package com.cjack.frenchexcel.util;

import java.awt.image.BufferedImage;
import java.awt.image.RenderedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;

import net.coobird.thumbnailator.Thumbnails;
import org.icepdf.core.exceptions.PDFException;
import org.icepdf.core.exceptions.PDFSecurityException;
import org.icepdf.core.pobjects.Document;
import org.icepdf.core.pobjects.Page;
import org.icepdf.core.util.GraphicsRenderingHints;

/**
 * @author: Luckly
 * @Description: pdf 转单张高清图片
 * @Date 2019-05-27
 * @Modified By:
 */
public class IcePdf {

    /**
     *
     * pdf转图片
     * @param pdfPath  pdf地址，目前只支持单页的pdf
     * @throws IOException
     * @throws PDFException
     * @throws PDFSecurityException
     * @throws InterruptedException
     */
    public static String pdf2Pic( String pdfPath, String serverImgFileDir, String clientImgFileDir) throws IOException, PDFException, PDFSecurityException, InterruptedException {
        Document document = new Document();
        document.setFile(pdfPath);
        //缩放比例
        float scale = 2.5f;
        //旋转角度document
        float rotation = 0f;
        String serverImgPaths = "";
        //for循环在pdf文件资料中使用，目前税票就固定一张，所有就注释了
        for (int i = 0; i < document.getNumberOfPages(); i++) {
            BufferedImage image = (BufferedImage) document.getPageImage(i, GraphicsRenderingHints.SCREEN, Page.BOUNDARY_CROPBOX, rotation, scale);
            RenderedImage rendImage = image;

            try {
                String fileName = System.currentTimeMillis() + "_" + ( i + 1) + ".jpg";
                String serverFilePath = serverImgFileDir + fileName;
                String clientFilePath = clientImgFileDir + fileName;
                File file = new File( serverFilePath);
                ImageIO.write( rendImage, "jpg", file);
                serverImgPaths += clientFilePath + ";";
            } catch (IOException e) {
                e.printStackTrace();
            }
            image.flush();
        }
        document.dispose();
        return serverImgPaths;
    }

    public static void main(String[] args) throws InterruptedException, PDFSecurityException, PDFException, IOException {
        String filePath = "/opt/frenchProjectFile/sellInvoice/2020-02-27/01358cfe-2153-44b2-aab8-003d413f3091.docx";
        String paths = pdf2Pic( filePath, "/opt/tt/", "/");
        Thumbnails.of("/opt/PT-011001900321-18675195.jpg")
                .scale(0.5f)
                .outputQuality(1f)
                .toFile("/opt/PT-011001900321-18675195_new.jpg");
    }
}
